package com.ruoyi.guanfei.service.impl;

import java.util.List;

import cn.hutool.extra.pinyin.PinyinUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.guanfei.mapper.BasicFarmMapper;
import com.ruoyi.guanfei.domain.BasicFarm;
import com.ruoyi.guanfei.service.IBasicFarmService;

/**
 * 农机信息Service业务层处理
 *
 * @author ruoyi
 * @date 2021-06-17
 */
@Service
public class BasicFarmServiceImpl implements IBasicFarmService
{
    @Autowired
    private BasicFarmMapper basicFarmMapper;


    /**
     * 查询农机信息
     *
     * @param id 农机信息ID
     * @return 农机信息
     */
    @Override
    public BasicFarm selectBasicFarmById(Long id)
    {
        return basicFarmMapper.selectBasicFarmById(id);
    }

    /**
     * 查询农机信息列表
     *
     * @param basicFarm 农机信息
     * @return 农机信息
     */
    @Override
    public List<BasicFarm> selectBasicFarmList(BasicFarm basicFarm)
    {
        return basicFarmMapper.selectBasicFarmList(basicFarm);
    }

    /**
     * 新增农机信息
     *
     * @param basicFarm 农机信息
     * @return 结果
     */
    @Override
    public int insertBasicFarm(BasicFarm basicFarm)
    {
        //农机编码自动生成
        createFarmCode(basicFarm);
        return basicFarmMapper.insertBasicFarm(basicFarm);
    }

    /**
     * 修改农机信息
     *
     * @param basicFarm 农机信息
     * @return 结果
     */
    @Override
    public int updateBasicFarm(BasicFarm basicFarm)
    {
        //更改农机类型需要重新生成编码
        return basicFarmMapper.updateBasicFarm(basicFarm);
    }

    /**
     * 批量删除农机信息
     *
     * @param ids 需要删除的农机信息ID
     * @return 结果
     */
    @Override
    public int deleteBasicFarmByIds(Long[] ids)
    {
        return basicFarmMapper.deleteBasicFarmByIds(ids);
    }

    /**
     * 删除农机信息信息
     *
     * @param id 农机信息ID
     * @return 结果
     */
    @Override
    public int deleteBasicFarmById(Long id)
    {
        return basicFarmMapper.deleteBasicFarmById(id);
    }

    /**
     * 生成农机编码
     * @param basicFarm 农机对象
     */
    private synchronized void createFarmCode(BasicFarm basicFarm){
        //编码前两位为农机类型拼音大写
        String pref = PinyinUtil.getFirstLetter(basicFarm.getCode(),"").toUpperCase().substring(0,2);
        BasicFarm maxBasicFarm = basicFarmMapper.selectBasicFarmMaxCodeByType(basicFarm.getType());
        StringBuilder code = new StringBuilder();
        if(maxBasicFarm == null){
            //没有新增数据时
            code =  new StringBuilder("00001");
        }else{
            int maxCode = Integer.parseInt(maxBasicFarm.getCode());
            String maxStrCode = String.valueOf(maxCode+1);
            //填充至五位
            for (int i=0;i<(5-maxStrCode.length());i++){
                code.append("0");
            }
            code.append(maxStrCode);
        }
        basicFarm.setCode(pref+code);
    }
}
